<template>
  <div>
    <div class="search_box">
      <p>设备型号：</p>
      <el-input v-model="input" placeholder="请输入内容"></el-input>
      <el-button
        type="primary"
        icon="el-icon-search"
        style="background: #5c84ff"
        @click="queryVmModel"
        >查询</el-button
      >
    </div>
    <div class="table_box">
      <div class="btn">
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          style="background: linear-gradient(to right, #ff8f3e, #ff6927)"
          @click="addVmModel"
          >新建</el-button
        >
        <!-- <el-button style="background: #fcf4ef" @click="batch"
          >批量操作</el-button
        > -->
      </div>
      <el-table
        :data="vmModelList"
        style="width: 100%; color: #666,border-bottom:none"
        :border="false"
        :header-cell-style="{ background: '#f3f6fa', color: '#666' }"
        ref="tableRef"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          width="80"
          :index="indexMethod"
        ></el-table-column>
        <el-table-column prop="name" label="型号名称"> </el-table-column>
        <el-table-column prop="model" label="型号编码"> </el-table-column>
        <el-table-column prop="image" label="设备图片">
          <template #default="scope">
            <img
              :src="scope.row.image"
              alt=""
              style="height: 24px; width: 24px; border-radius: 50%"
            />
          </template>
        </el-table-column>
        <el-table-column prop="vmRow" label="货道行"> </el-table-column>
        <el-table-column prop="vmCol" label="货道列"> </el-table-column>
        <el-table-column prop="channelMaxCapacity" label="设备容量">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <!-- 通过插槽获取单行的数据 -->
          <template #default="scope">
            <el-button
              type="text"
              style="padding: 0"
              @click="editVmModel(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              style="padding: 0; color: red"
              @click="del(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-container" v-if="vmModelList.length !== 0">
        <el-pagination layout="slot">
          <template>
            <span
              >共{{ page.totalCount }}条记录 第{{ page.pageIndex }}/{{
                page.totalPage
              }}页</span
            >
            <div class="btn">
              <button
                :disabled="page.pageIndex === '1'"
                @click="change_page(-1)"
              >
                上一页
              </button>
              <button
                :disabled="page.totalPage === page.pageIndex"
                @click="change_page(1)"
              >
                下一页
              </button>
            </div>
          </template>
        </el-pagination>
      </div>
    </div>

    <!-- 新建类型弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="630px"
      @close="handleClose"
    >
      <el-form label-width="100px" :model="form" :rules="rules" ref="formRef">
        <el-form-item label="型号名称：" prop="name">
          <el-input
            v-model.trim="form.name"
            show-word-limit
            maxlength="10"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="型号编码：" prop="model">
          <el-input
            v-model.trim="form.model"
            show-word-limit
            maxlength="15"
            placeholder="请输入(限制数字、字母、中划线、下划线)"
          ></el-input>
        </el-form-item>
        <el-form-item label="货道行数：" prop="vmRow">
          <el-input v-model.trim="form.vmRow" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="货道列数：" prop="vmCol">
          <el-input v-model.trim="form.vmCol" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="货道容量：" prop="channelMaxCapacity">
          <el-input
            v-model.trim="form.channelMaxCapacity"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="设备图片：">
          <el-upload
            class="avatar-uploader"
            action="http://likede2-admin.itheima.net/likede/api/vm-service/sku/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="fileName"
            ref="uploadRef"
          >
            <img v-if="form.image" :src="form.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过100kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="enterAddVmModel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getVmModel,
  delVmModel,
  addVmModel,
  editVmModel
} from '@/api/equipment'
import { Message } from 'element-ui'
export default {
  name: 'equipment-page',
  created() {
    this.getVmModel()
  },

  data() {
    // 自定义校验
    const validateChannelMaxCapacity = (rule, value, callback) => {
      console.log()
      if (Number(value)) {
        if (value > 10) {
          this.form.channelMaxCapacity = 10
        }
        callback()
      } else {
        this.form.channelMaxCapacity = ''
        callback(new Error('只能为数字'))
      }
    }

    const validateVmCol = (rule, value, callback) => {
      console.log()
      if (Number(value)) {
        if (value > 10) {
          this.form.vmCol = 10
        }
        callback()
      } else {
        this.form.vmCol = ''
        callback(new Error('只能为数字'))
      }
    }

    const validateVmRow = (rule, value, callback) => {
      console.log()
      if (Number(value)) {
        if (value > 10) {
          this.form.vmRow = 10
        }
        callback()
      } else {
        this.form.vmRow = ''
        callback(new Error('只能为数字'))
      }
    }

    return {
      // 新建弹窗
      dialogVisible: false,
      title: '新增设备类型',
      form: {
        channelMaxCapacity: '',
        image: '',
        model: '',
        name: '',
        vmCol: '',
        vmRow: ''
      },
      typeId: '',
      rules: {
        channelMaxCapacity: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { validator: validateChannelMaxCapacity, trigger: 'blur' }
        ],
        image: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        model: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9-_]+$/,
            message: '编码只能为数字、字母、中划线、下划线',
            trigger: 'blur'
          }
        ],
        name: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
        vmCol: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { validator: validateVmCol, trigger: 'blur' }
        ],
        vmRow: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { validator: validateVmRow, trigger: 'blur' }
        ]
      },
      // 每页数量
      page: {
        pageIndex: '1',
        pageSize: '10',
        totalCount: '110',
        totalPage: '11'
      },

      // 输入框
      input: '',
      // 设备列表
      vmModelList: [],

      // 图片上传
      imageUrl: ''
    }
  },
  methods: {
    // 获取页面数据
    async getVmModel(obj) {
      try {
        const res = await getVmModel(obj)
        console.log('设备列表', res)
        this.page = {
          pageIndex: res.pageIndex,
          pageSize: res.pageSize,
          totalCount: res.totalCount,
          totalPage: res.totalPage
        }
        this.vmModelList = res.currentPageRecords
      } catch (error) {}
    },

    // 下一页上一页
    change_page(num) {
      this.page.pageIndex = Number(this.page.pageIndex) + num
      const obj = {
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize
      }
      this.getVmModel(obj)
    },

    // 查询设备
    queryVmModel() {
      const obj = {
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize,
        name: this.input
      }
      this.getVmModel(obj)
    },

    // 表格序号
    indexMethod(index) {
      // 当前页数减一 乘以 每页个数 加 索引值(从零开始）+1
      return (this.page.pageIndex - 1) * this.page.pageSize + index + 1
    },

    // 图片上传 组件 action 设置为后台图片上传接口 图片上传成功后 服务器会返回图片链接 使用属性 on-success（上传成功钩子函数） 接收
    handleAvatarSuccess(res, file) {
      this.form.image = res
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'

      const isLt2M = 100 - file.size / 1024 >= 0

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 100kb!')
      }
      return isJPG && isLt2M
    },

    // 删除设备类型
    async del(row) {
      await delVmModel(row.typeId)
      this.getVmModel({
        pageIndex: this.page.pageIndex,
        pageSize: this.page.pageSize
      })
      Message.success('删除成功')
    },

    // 修改设备类型
    editVmModel(row) {
      this.title = '修改设备类型'
      this.typeId = row.typeId
      this.$nextTick(() => {
        this.form.channelMaxCapacity = String(row.channelMaxCapacity)
        this.form.image = row.image
        this.form.model = row.model
        this.form.name = row.name
        this.form.vmCol = String(row.vmCol)
        this.form.vmRow = String(row.vmRow)
      })

      this.dialogVisible = true
    },

    // 新增设备类型
    async addVmModel() {
      this.title = '新增设备类型'
      this.form.image = ''
      this.dialogVisible = true
    },
    async enterAddVmModel() {
      try {
        let message = ''
        if (this.title === '新增设备类型') {
          await addVmModel(this.form)
          message = '新建成功'
        } else {
          await editVmModel(this.form, this.typeId)
          message = '修改成功'
        }
        this.dialogVisible = false

        this.getVmModel()
        this.$message.success(message)
      } catch (error) {
        this.$message.error(error.response.data)
      }
    },
    // 弹窗关闭时的回调
    handleClose() {
      this.$refs.formRef.resetFields()
      this.getVmModel()
    }
  }
}
</script>

<style scoped lang="scss">
// 按钮通用样式
.el-button {
  padding: 10px 16px;
  border: none;
}
// 查询
.search_box {
  display: flex;
  align-items: center;
  height: 64px;

  margin-bottom: 20px;
  padding-left: 17px;
  .el-input {
    width: 200px;
    margin-right: 10px;
  }
  p {
    padding-right: 12px;
  }
}
// 表格
.table_box {
  padding: 20px 0 0 17px;
  .btn {
    margin-bottom: 20px;
  }
}
::v-deep .el-table th.el-table__cell.is-leaf {
  border: none;
}
::v-deep .el-table td.el-table__cell {
  border: none;
}

.el-table::before {
  height: 0px;
}
.pagination-container {
  padding: 32px 16px;
  width: 100%;
  span {
    float: left;
  }
  .btn {
    float: right;
  }
}

::v-deep .el-dialog {
  border-radius: 8px;
}
.el-form-item {
  padding: 0 32px;
}

//图片上传
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
::v-deep .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 86px;
  height: 86px;
  line-height: 86px;
  text-align: center;
}
::v-deep .avatar {
  width: 86px;
  height: 86px;
  display: block;
}
</style>
